package com.itheima.interceptor;


import com.alibaba.fastjson.JSON;
import com.aliyuncs.utils.StringUtils;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
@Component
public class Interceptors implements HandlerInterceptor {


    @Override
    public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");
        // 预处理，比如登录验证，权限验证等
        //如果校验通过，返回true，如果校验不通过，返回false，阻止请求继续执行
        String url = request.getRequestURI();
        System.out.println("请求的url是：" + url);

        if (url.contains("login")){
            log.info("登录页面，放行");
            return true;
        }

        //判断是否token是否存在
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            //未登录，重定向到登录页面
            Result result = new Result();
            result.setCode(401);
            result.setMessage("请先登录");
            result.setData(null);

            //需要把result对象序列化成json字符串，并设置到response的body中
            //利用fastjson
            String error = JSON.toJSONString(result);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(error);
            return false;
        }
        //判断token是否有效
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            //token无效，重定向到登录页面
            Result result = new Result();
            result.setCode(401);
            result.setMessage("请先登录");
            result.setData(null);

            //需要把result对象序列化成json字符串，并设置到response的body中
            //利用fastjson
            String error = JSON.toJSONString(result);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(error);
            return false;
        }

        System.out.println("过滤器工作结束");
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }
}
